<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <el-select v-model="choosedwebsites" filterable clearable placeholder="请选择" style="width: 70%" @change="handleSelectedChange">
          <el-option
            v-for="item in websites"
            :key="item.id"
            :label="item.domain"
            :value="item.id"
          />
        </el-select>
        <el-button
          v-if="choosedwebsites"
          v-loading="listLoading"
          icon="el-icon-refresh"
          type="success"
          plain
          @click="sync('catalog')"
        >crawl_url_temp
        </el-button>
      </el-header>
      <el-container>
        <el-aside v-loading="categoryloading" :width="leftwidth" style="border-right: solid">
          <el-input
            v-if="categories.length"
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            size="mini"
            style="padding:10px"
            clearable
          />
          <el-tree
            ref="categoryTree"
            :data="categories"
            show-checkbox
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterCategoryNode"
            :props="{ children: 'children', label: 'name' }"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node" style="float: right">
              <span>{{ data.name+" (ID:"+data.id+")" }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="() => append(data)"
                >
                  <i class="el-icon-plus" />
                </el-button>
              </span>
            </span>
          </el-tree></el-aside>
        <el-main v-loading="detailloading">
          <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="150px" label-position="right">
            <el-form-item label="ID" prop="id" disabled>
              <el-input v-model="form.id" disabled />
            </el-form-item>
            <el-form-item label="父级目录ID" prop="id">
              <el-input v-model="form.id_parent" />
            </el-form-item>
            <el-form-item label="name" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>

            <el-form-item label="显示">
              <el-switch v-model="form.active" />
            </el-form-item>
            <el-form-item label="meat title" prop="meta_title">
              <el-input v-model="form.meta_title" />
            </el-form-item>
            <el-form-item label="meat description" prop="meta_description">
              <el-input v-model="form.meta_description" />
            </el-form-item>
            <el-form-item label="meat keywords">
              <el-input v-model="form.meta_keywords" />
            </el-form-item>
            <el-form-item label="Friendly URL">
              <el-input v-model="form.friendly_url" />
            </el-form-item>
            <el-form-item label="description" prop="desc">
              <tinymce ref="mt" v-model="form.description" :height="300" />
            </el-form-item>
            <el-form-item>
              <el-button v-if="delateables" type="danger" @click="deleteCategory">删除此目录</el-button>
              <el-button style="float: right">取消</el-button>
              <el-button style="float: right" type="primary" @click="onSubmit">{{ edittext }}</el-button>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {
  CatalogTree as GetWebsiteCatalogs,
  GetCategoryDetail,
  AddCategory,
  DeleteCategory,
  Sync
} from '@/api/erp/elicink/website'
import Tinymce from '@/components/Tinymce'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
let id = 1000000
const _ = require('lodash')
export default {
  name: 'Category',
  components: { Tinymce },
  data() {
    return {
      filterText: '',
      listLoading: false,
      categoryloading: false,
      websites: [],
      choosedwebsites: '',
      categories: [],
      // form data
      detailloading: false,
      edittext: '创建目录',
      leftwidth: '100%',
      delateables: false,
      form: {
        id: 'dd',
        id_parent: '',
        name: 'new category name',
        title: 'new xxx category name',
        active: true,
        website_id: '',
        description: '',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        coverimagurl: '',
        friendly_url: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 1, max: 1000, message: '长度在 0 到 1000 个字符', trigger: 'blur' }
        ],
        meta_title: [
          { required: true, message: '请输入meta title', trigger: 'blur' },
          { min: 1, max: 70, message: '长度在 0 到 70 个字符', trigger: 'blur' }
        ],
        meta_description: [
          { required: true, message: '请输入meta description', trigger: 'blur' },
          { min: 1, max: 160, message: '长度在 0 到 160 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请填写描述', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'form.name': function(val) {
      if (val) this.form.friendly_url = _.trim(this.form.name, '-').split(' ').join('-')
    },
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },

  created() {
    GetWebsite().then(response => {
      this.websites = response.data.data
    })
  },
  methods: {
    sync(mode) {
      this.listLoading = true
      Sync(mode, this.choosedwebsites).then(response => {
        this.listLoading = false
        this.$message({
          type: 'success',
          message: '同步成功'
        })
        this.GetCategorys()
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleSelectedChange() {
      this.GetCategorys()
    },
    append(data) {
      this.form.id_parent = data.id
      this.leftwidth = '30%'
      this.delateables = false
      const newChild = { id: id++, name: '新目录', children: [] }
      this.form.id = newChild.id
      this.form.name = newChild.name
      console.log('parent', this.form.id_parent)
      if (this.form.id_parent >= 1000000) {
        this.$message({
          type: 'success',
          message: '父级目录还未保存，不能创建子目录!'
        })
        return
      }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },
    deleteCategory() {
      this.$confirm(`此操作将永久删除目录[${this.form.name}], 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteCategory(Object.assign(this.form,
          { website_id: this.choosedwebsites }))
          .then(response => {
            this.detailloading = false
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.GetCategorys()
          })
          .catch(e => {
            this.detailloading = false
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          })
          // const parent = this.form.id_parent;
          // const children = parent.children;
          // const index = children.findIndex(this.form.id);
          // children.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1 || String(data.id).toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1
    },
    handleNodeClick(data) {
      this.form.id = data.id
      this.leftwidth = '30%'
      if (this.form.id < 1000000) {
        this.detailloading = true
        GetCategoryDetail({ wid: this.choosedwebsites, cid: data.id }).then(respone => {
          this.$refs.form.clearValidate()
          this.form = respone.data
          this.form.active = this.form.active === '1'
          this.form.website_id = this.choosedwebsites
          this.detailloading = false
          this.$nextTick(() => {
            this.$refs.mt.setContent(this.form.description)
          })
        })
        this.delateables = true
        this.edittext = '提交修改'
      } else {
        this.delateables = false
        this.edittext = '新增目录'
        this.form.name = data.name
      }

      console.log(this.form)
    },
    onSubmit() {
      if (this.form.id >= 1000000) {
        this.form.id = ''
      }
      this.detailloading = true
      this.form.active = this.form.active ? '1' : '0'
      AddCategory(Object.assign(this.form,
        { website_id: this.choosedwebsites }))
        .then(response => {
          this.form.active = this.form.active === '1'
          this.detailloading = false
          this.$message({
            type: 'info',
            message: '保存成功'
          })
          this.GetCategorys()
        })
        .catch(e => {
          this.detailloading = false
          this.$message({
            type: 'error',
            message: '保存失败'
          })
        })
    },
    GetCategorys() {
      this.categoryloading = true
      GetWebsiteCatalogs(this.choosedwebsites).then(respone => {
        this.categories = respone.data
        this.form.website_id = this.choosedwebsites
        this.categoryloading = false
      })
    }
  }
}
</script>

<style scoped>
.el-form-item {
    margin-bottom: 10px;
}
</style>
